package com.xiaocg.singleton;

/**
 * 单例模式 -- 懒汉式
 * 线程安全与否
 */
public class SlackerSingleton {

    private SlackerSingleton(){}

    private static volatile SlackerSingleton instance1;
    private static SlackerSingleton instance;

    /**
     * 方式一
     * @return
     */
    public static SlackerSingleton getSlackerSingleton(){
        if (instance == null){
            instance = new SlackerSingleton();
        }
        return instance;
    }


    /**
     * 方式二 加锁，对静态方法加锁，锁对象是类对象
     * @return
     */
    public static synchronized SlackerSingleton getSlackerSingleton2(){
        if (instance == null){
            instance = new SlackerSingleton();
        }
        return instance;
    }

    /**
     * 方式三 双重检测 定义的变量需要加上volatile 关键字，多线程环境下保证cpu指令的可见性和有序性
     * @return
     */
    public static SlackerSingleton getSlackerSingleton1(){
        if (instance1 == null){
            synchronized (SlackerSingleton.class){
                if (instance1 == null){
                    instance1 = new SlackerSingleton();
                }
            }
        }
        return instance1;
    }
}
